<?php
namespace app\api\controller\vppz;


use think\Cache;


use \app\admin\model\vppz\User as UserModel;
use \app\admin\model\vppz\Staff as StaffModel;
use \app\admin\model\vppz\Order as OrderModel;
use \app\admin\model\vppz\OrderCheck as OrderCheckModel;

use think\Db;
use EasyWeChat\Factory as EasyWeChatFactory;

use \addons\vppz\library\Vpower;

class Staff extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


	protected $_staff = null;

    public function _initialize(){
        parent::_initialize();

		$this->UserModel = new UserModel;
		$this->StaffModel = new StaffModel;
		$this->OrderModel = new OrderModel;
		$this->OrderCheckModel = new OrderCheckModel;

		$mine=$this->_mine;

		// 获取我的服务员身份信息
		$staff = $this->StaffModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id']])->find();

		// 除了注册，其他需验证是否陪护师
		if(!in_array($this->request->action(),['index','reg','personreg','getstaffinfo']) && (empty($staff) || $staff['status']!=20)){
			$this->error('您不是陪护师，无法访问');
		}

		if($staff && $staff['stop_switch']==1){
			$this->error('您已被停用陪护师权限，如有疑问请联系平台客服');
		}

		$this->_staff=$staff;

    }


    /**
     * 陪护师首页
     */
    public function index(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		// 我是否有当前正在进行的订单
		$statistic=array();
		// 待服务
		$statistic['todos'] = $this->OrderModel->where(['app_id'=>$this->app_id,'staff_uid'=>$mine['id'],'status'=>20,'staff_status'=>10])->count();

		// 如果是派单模式，将同城可接单陪护师提供到前端
		$staffs=array();
		if($area['odmode']==10){
			//$staffs = pdo_fetchall('SELECT id,uid,nickname,avatar,sex,age,mobile,realname FROM ' .tablename('vp_pz_staff') . ' where uniacid = :uniacid AND city_id=:city_id AND status=20 AND is_dis=0 ', array(':uniacid' => $_W['uniacid'],':city_id'=>$area['id']));
			$staffs = $this->StaffModel->field('id,user_id,nickname,avatar,sex,age,mobile,realname')->where(['app_id'=>$this->app_id,'area_id'=>$area['id'],'status'=>20,'stop_switch'=>0])->select();
		}

		$this->success('',array(
			'now'=>time(),
			'staff'=>$staff,
			'statistic'=>$statistic,
			'staffs'=>$staffs
		));
    }

    //获取陪护师信息
    public function getStaffInfo(){
        $input = input();
        $ret=$this->StaffModel->where('user_id',$input['user_id'])->find();
        if(empty($ret)){
            $this->success('',array(
                'code'=>0,
                'data'=>[]
            ));
        }else{
            $this->success('',array(
                'code'=>1,
                'data'=>$ret
            ));
        }
    }
    /**
     * 陪护师名片页
     */
    public function card(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		// 统计我已经有多少客户
		$users = $this->UserModel->where(['app_id'=>$this->app_id,'my_staff_id'=>$staff['id']])->count();

		$this->success('',array(
			'now'=>time(),
			'staff'=>$staff,
			'users'=>$users
		));
    }
    //陪护师个人认证
    public function personReg(){
        $area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;
        $submit=input('submit');

		if($submit=='save'){
            $avatarUrl = input('avatarUrl');
            $phone = input('phone');
            $nickName = input('nickName');
            $gender = input('gender',1);
			if(empty($avatarUrl) || empty($phone) || empty($nickName)){
				$this->error("内容填写有误，请重试");
			}
            //入库
            $master_uid=0;
            $staff=array(
                'app_id'=>$this->app_id,
                'area_id'=>$area['id'],
                'user_id'=>$mine['id'],
                'openid'=>$mine['openid'],
                'nickname'=>$nickName,
                'avatar'=>$avatarUrl,
                'sex'=>$gender,
                'age'=>0,
                'mobile'=>$phone,
                'realname'=>0,
                'idcardnum'=>0,
                'is_qiye'=>0,
                'yingyezhizhao'=>'',
                'idcards_images'=>'',//serialize(array('idcard1'=>$form['idcard1'],'idcard2'=>$form['idcard2'])),	// 是否应该逗号分隔?
                'master_uid'=>$master_uid,
                'status'=>10,
                'status_time'=>time()
            );

            $ret=$this->StaffModel->save($staff);
            $staff['id'] = $this->StaffModel->id;
            if(empty($ret) || empty($staff['id'])){
                $this->error('服务器刚刚走神了，重试看看呢');
            }

            $this->success('请耐心等待平台审核，约1~2个工作日。审核期间可能会联系您确认信息，请保持手机通畅');
        }
    }

	/**
     * 企业陪护师注册
     */
    public function reg(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		$submit=input('submit');

		if($submit=='save'){
			// 接受参数
			$form = input('form');
			if(empty($form)){
				$this->error("内容填写有误，请重试");
			}
			$form = json_decode(urldecode($form),true);
			if(!$form){
				$this->error("内容填写有误，请重试");
			}

			// $this->error("数据回传",$form);

			// 参数验证
			if(empty($form['avatar'])){
				$this->error("请上传您的形象照片");
			}

			if(empty($form['nickname'])){
				$this->error("请填写您的称呼");
			}
			if(mb_strlen($form['nickname'])<2){
				$this->error("称呼至少2个字");
			}
			if(mb_strlen($form['nickname'])>10){
				$this->error("称呼最多10个字");
			}

			if(empty($form['mobile'])){
				$this->error("请填写您的手机号");
			}
			if(empty($form['realname'])){
				$this->error("请填写您的身份证名称");
			}
			if(empty($form['idcardnum'])){
				$this->error("请填写您的身份证号");
			}
			if(empty($form['idcard1'])){
				$this->error("请上传身份证正面照片");
			}
			if(empty($form['idcard2'])){
				$this->error("请上传身份证背面照片");
			}

			if(empty($form['is_qiye'])){
				$this->error("请选择认证类型");
			}
            if($form['is_qiye'] == 1){
                if(empty($form['yingyezhizhao'])){
                    $this->error("请上传营业执照");
                }
            }
			if(empty($staff)){
				// 新注册

				// 邀请码验证解析
				if($area['staff_reg']==3){
					if(empty($form['invite_code'])){
						$this->error("请填写邀请码");
					}
				}

				$master_uid=0;
				if($area['staff_reg']>1 && !empty($form['invite_code'])){
					$invite_code = Vpower::pdecode($form['invite_code']);
					$master_uid=intval($invite_code);
					if(empty($invite_code) || !($master_uid>0)){
						$this->error("邀请码不正确");
					}
					// 获取邀请人
					//$master = pdo_fetch('SELECT * FROM ' .tablename('vp_pz_staff') . ' where  uniacid = :uniacid AND uid=:uid ', array(':uniacid' => $_W['uniacid'],':uid'=>$master_uid));
					$master = $this->StaffModel->where(['app_id'=>$this->app_id,'user_id'=>$master_uid])->find();
					if(empty($master)){
						$this->error("该邀请码无效");
					}

					// 增加邀请人团员数
					Db::name('vppz_staff')->where(['app_id'=>$this->app_id,'id'=>$master['id']])->inc('subs',1)->update();
				}

				$staff=array(
					'app_id'=>$this->app_id,
					'area_id'=>$area['id'],
					'user_id'=>$mine['id'],
					'openid'=>$mine['openid'],
					'nickname'=>$form['nickname'],
					'avatar'=>$form['avatar'],
					'sex'=>intval($form['sex']),
					'age'=>intval($form['age']),
					'mobile'=>$form['mobile'],
					'realname'=>$form['realname'],
					'idcardnum'=>$form['idcardnum'],
					'is_qiye'=>$form['is_qiye'],
					'yingyezhizhao'=>$form['yingyezhizhao']??'',
					'idcards_images'=>implode(',',array('idcard1'=>$form['idcard1'],'idcard2'=>$form['idcard2'])),//serialize(array('idcard1'=>$form['idcard1'],'idcard2'=>$form['idcard2'])),	// 是否应该逗号分隔?
					'master_uid'=>$master_uid,
					'status'=>10,
					'status_time'=>time()
				);

				$ret=$this->StaffModel->save($staff);
				$staff['id'] = $this->StaffModel->id;
				if(empty($ret) || empty($staff['id'])){
					$this->error('服务器刚刚走神了，重试看看呢');
				}

				$this->success('请耐心等待平台审核，约1~2个工作日。审核期间可能会联系您确认信息，请保持手机通畅');
			}else{
				// 修改
				$staffUp=array(
					'nickname'=>$form['nickname'],
					'avatar'=>$form['avatar'],
					'sex'=>intval($form['sex']),
					'age'=>intval($form['age']),
					'mobile'=>$form['mobile'],
					'realname'=>$form['realname'],
					'idcardnum'=>$form['idcardnum'],
					'is_qiye'=>$form['is_qiye'],
					'yingyezhizhao'=>$form['yingyezhizhao'],
					'idcards_images'=>implode(',',array('idcard1'=>$form['idcard1'],'idcard2'=>$form['idcard2'])),//serialize(array('idcard1'=>$form['idcard1'],'idcard2'=>$form['idcard2'])),	// 是否应该逗号分隔?
					'status'=>10,
					'status_time'=>time(),
				);

				$ret = $this->StaffModel->save($staffUp,['id'=>$staff['id']]);

				if(!($ret>0)){
					$this->error("保存失败，请重试");
				}
				$this->success('已提交审核');
			}
		}else{
			// 处理内容
			if(!empty($staff)){
				$idcards = explode(',',$staff['idcards_images']);
				$staff['idcard1']=$idcards[0];
				$staff['_idcard1']=\addons\vppz\library\Vpower::dourl($idcards[0]);
				$staff['idcard2']=$idcards[1];
				$staff['_idcard2']=\addons\vppz\library\Vpower::dourl($idcards[1]);

				$staff['yingyezhizhao']=$staff['yingyezhizhao'];
				$staff['_yingyezhizhao']=\addons\vppz\library\Vpower::dourl($staff['yingyezhizhao']);

				/**
				for($i=0;$i<count($imgs);$i++){
					$urls[]=\addons\vppz\library\Vpower::dourl($imgs[$i]);
				}

				$staff['idcards_images_urls']=$urls
				**/
			}

			$this->success('',array(
				'now'=>time(),
				'staff'=>$staff
			));
		}
    }

	/**
     * 修改资料
     */
    public function profile(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		$submit=input('submit');
		if($submit=='save'){
			// 接受参数
			$form = input('form');
			if(empty($form)){
				return $this->error("内容填写有误，请重试");
			}
			$form = json_decode(urldecode($form),true);
			if(!$form){
				return $this->error("内容填写有误，请重试");
			}

			// return $this->error("数据回传",$form);

			// 参数验证
			if(empty($form['avatar'])){
				return $this->error("请上传您的形象照片");
			}

			if(empty($form['nickname'])){
				return $this->error("请填写您的称呼");
			}
			if(mb_strlen($form['nickname'])<2){
				return $this->error("称呼至少2个字");
			}
			if(mb_strlen($form['nickname'])>10){
				return $this->error("称呼最多10个字");
			}

			if(empty($form['mobile'])){
				return $this->error("请填写您的手机号");
			}


			$staffUp=array(
				'nickname'=>$form['nickname'],
				'avatar'=>$form['avatar'],
				'age'=>intval($form['age']),
				'mobile'=>$form['mobile']
			);

			$ret = $this->StaffModel->save($staffUp,['id'=>$staff['id']]);

			if(!($ret>0)){
				return $this->error("保存失败，请重试");
			}
			$this->success('保存成功');

		}else{
			$this->success('',array(
				'now'=>time(),
				'staff'=>$staff
			));
		}
	}

	//绑定公众号
	public function bindacc(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		$openid = input('openid');
		if(empty($openid)){
			return $this->error("openid获取失败，请重试");
		}

		$this->StaffModel->save(['acopenid'=>$openid],['id'=>$staff['id']]);

		$this->success('绑定成功');
	}


	/**
     * 订单大厅
     */
    public function orders_client(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		// 接单大厅
		$start=input('start');
		if(!isset($start) || empty($start) || intval($start<=0)){
			$start=0;
		}else{
			$start=intval($start);
		}
		$limit=20;

		$where=[
			'app_id'=>$this->app_id,
			'area_id'=>$area['id'],
			'status'=>20,
			'staff_status'=>0 // 已支付未接单的订单
		];

		$list = $this->OrderModel->where($where)->limit($start,$limit)->select();

		$more=1;
		if(empty($list) || count($list)<$limit){
			$more=0;
		}
		$start+=count($list);

		$this->success('',array(
			'now'=>time(),
			'list'=>$list,
			'start'=>$start,
			'more'=>$more
		));

	}

	/**
     * 我的订单
     */
    public function orders(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		// 我的订单
		$start=input('start');
		if(!isset($start) || empty($start) || intval($start<=0)){
			$start=0;
		}else{
			$start=intval($start);
		}
		$limit=20;


		$where=[
			'app_id'=>$this->app_id,
			'staff_status'=>['>',0],
			'staff_id'=>$staff['id']
		];

		// 全部，待支付，进行中，已完成，已取消
		$filt=input('filt');
		if(!empty($filt)){
			$where['status']=$filt;
		}

		// 获内容记录
		//$list =  pdo_fetchall('SELECT * FROM ' .tablename('vp_pz_order') . ' WHERE '. $where .' ORDER BY status_time DESC '.' limit '.$start.','.$limit.' ',$params);
		$list = $this->OrderModel->where($where)->limit($start,$limit)->select();

		for($i=0;$i<count($list);$i++){
			if($list[$i]['address']){
				$list[$i]['address']=unserialize($list[$i]['address']);
			}
		}

		$more=1;
		if(empty($list) || count($list)<$limit){
			$more=0;
		}
		$start+=count($list);

		$this->success('',array(
			'now'=>time(),
			'list'=>$list,
			'start'=>$start,
			'more'=>$more
		));
	}


	/**
     * 抢单
     */
    public function order_get(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		$oid = input('oid');
		if(empty($oid)){
			$this->error('缺少订单参数');
		}

		$order = $this->OrderModel->where(['app_id'=>$this->app_id])->find($oid);
		if(empty($order)){
			$this->error('该订单不存在或已取消');
		}

		if($order['status']!=20 || $order['staff_status']!=0){
			$this->error('该订单已被接单');
		}

		// 接单
		$ret = $this->OrderModel->save(['staff_status'=>10,'staff_id'=>$staff['id'],'staff_uid'=>$mine['id'],'staff_time'=>time()],['app_id'=>$this->app_id,'id'=>$order['id'],'staff_status' => 0]);

		if(!($ret>0)){
			$this->error("接单失败，请重试");
		}

		// 成功接单后，将用户的服务专员更新为当前接单者
		$this->UserModel->save(['my_staff_id'=>$staff['id']],['app_id'=>$this->app_id,'id'=>$order['user_id']]);

		$this->success("接单成功，请尽快联系客户进行服务确认");
	}

	/**
     * 派单
     */
	public function order_give(){
		$cfg=$this->_cfg;
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		$oid = input('oid');
		if(empty($oid)){
			$this->error('缺少订单参数');
		}

		$order = $this->OrderModel->where(['app_id'=>$this->app_id])->find($oid);
		if(empty($order)){
			$this->error('该订单不存在或已取消');
		}

		if($order['status']!=20 || $order['staff_status']!=0){
			$this->error('该订单已被接单');
		}

		// 被派单者
		$staff_id=input('staff_id');
		if(!($staff_id>0)){
			$this->error('请选择陪护师');
		}

		//$tostaff = pdo_fetch('SELECT * FROM ' .tablename('vp_pz_staff') . ' where  uniacid = :uniacid AND id=:id ', array(':uniacid' => $_W['uniacid'],':id'=>$staff_id));

		$tostaff = $this->StaffModel->where(['app_id'=>$this->app_id])->find($staff_id);

		if(empty($tostaff) || $tostaff['status']!=20){
			$this->error('该陪护师不存在或尚未审核通过');
		}
		if($tostaff['stop_switch']>0){
			$this->error('该陪护师已被停用');
		}

		// 派单
		$ret = $this->OrderModel->save(['staff_toid'=>$tostaff['id'],'staff_touid'=>$tostaff['user_id'],'staff_status'=>10,'staff_id'=>$tostaff['id'],'staff_uid'=>$tostaff['user_id'],'staff_time'=>time()],['app_id'=>$this->app_id,'id'=>$order['id'],'staff_status' => 0]);

		if(!($ret>0)){
			$this->error("派单失败，请重试");
		}

		// 派单后，将用户的服务专员更新为当前接单者
		$this->UserModel->save(['my_staff_id'=>$staff['id']],['app_id'=>$this->app_id,'id'=>$order['user_id']]);


		// 通知接单者
		if(!empty($cfg['nt_order_new'])){
			$pdata = [
				'first' => array(
					'value' => '有新的服务订单派达',
					'color' => '#f73959'
				),
				'keyword1' => array(
					'value' => $order['area_name']
				),
				'keyword2' => array(
					'value' => $order['title']
				),
				'keyword3' => array(
					'value' => '等待处理'
				),
				'remark' => array(
					'value' => '点击前往查看处理'
				)
			];

			// 新-公众号模板消息
			$acc = EasyWeChatFactory::officialAccount(['app_id' => $cfg['mpappid'],'secret' => $cfg['mpappsecret']]);
			$ret = $acc->template_message->send([
				'touser' => $tostaff['acopenid'],
				'template_id' => $cfg['nt_order_new'],
				'miniprogram' => [
						'appid' => $cfg['wxapp_id'],
						'pagepath' => 'vp_pz/pages/staff/index',
				],
				'data' => $pdata
			]);


			/** 原-统一模板消息
			$WxappApi = EasyWeChatFactory::miniProgram([
				'app_id'    => $this->_cfg['wxapp_id'],
				'secret'    => $this->_cfg['wxapp_secret']
			]);
			$ret = $WxappApi->uniform_message->send([
				'touser' => $tostaff['openid'],
				'mp_template_msg'=>[
					'appid'=>$this->_cfg['mpappid'],
					'template_id'=>$this->_cfg['nt_order_new'],
					'miniprogram'=>array(
						'appid'=>$this->_cfg['wxapp_id'],
						'pagepath'=>'vp_pz/pages/staff/index',
					),
					'data'=>$pdata
				]
			]);
			**/





		}


		$this->success("派单成功");
	}

	/**
     * 订单详情与处理
     */
	public function order(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		$oid = input('oid');
		if(empty($oid)){
			$this->error('缺少订单参数');
		}

		$order = $this->OrderModel->where(['app_id'=>$this->app_id])->find($oid);
		if(empty($order)){
			$this->error('该订单不存在或已取消');
		}

		if($order['staff_id']!=$staff['id']){
			$this->error('您不是该订单服务承接者，无权操作');
		}

		$submit=input('submit');
		if($submit=='cancel'){
			if($order['status']!=20 || !($order['staff_status']>0)){
				$this->error('订单状态发生变化，请刷新后重试');
			}

			// 弃单
			$ret = $this->OrderModel->save(['staff_toid'=>0,'staff_touid'=>0,'staff_status'=>0,'staff_id'=>0,'staff_uid'=>0,'staff_time'=>time()],['app_id'=>$this->app_id,'id'=>$order['id']]);

			if(!($ret>0)){
				$this->error("操作失败，请重试");
			}

			$this->success("已放弃该订单");
		}else if($submit=='checks'){

			// 获内容记录
			//$list =  pdo_fetchall('SELECT * FROM ' .tablename('vp_pz_order_check') . ' WHERE uniacid = :uniacid AND order_id=:order_id order by id desc ',array('uniacid' => $_W['uniacid'],':order_id'=>$oid));
			$list = $this->OrderCheckModel->where(['app_id'=>$this->app_id,'order_id'=>$order['id']])->order('id','DESC')->select();
			/**
			for($i=0;$i<count($list);$i++){
				$list[$i]['images']=unserialize($list[$i]['images']);
				$list[$i]['postion']=unserialize($list[$i]['postion']);
			}
			**/
			$this->success('',array('list'=>$list));
		}else if($submit=='check'){

			$form = input('form');
			if(empty($form)){
				$this->error("内容填写有误，请重试");
			}
			$form = json_decode(urldecode($form),true);
			if(!$form){
				$this->error("内容填写有误，请重试");
			}

			// 参数验证
			if(empty($form['content']) && (empty($form['images']) || count($form['images'])==0)){
				$this->error("请用照片或文字记录服务进度");
			}

			// 记录
			$check=array(
				'app_id'=>$this->app_id,
				'area_id'=>$order['area_id'],
				'order_id'=>$order['id'],
				'staff_id'=>$staff['id'],
				'staff_uid'=>$mine['id'],
				'content'=>$form['content'],
				'images'=>serialize($form['images']),
				'postion'=>serialize($form['postion'])
			);
			$ret = $this->OrderCheckModel->save($check);
			$check['id'] = $this->OrderCheckModel->id;
			if(empty($ret) || empty($check['id'])){
				$this->error('服务器刚刚走神了，重试看看呢');
			}

			$this->success('服务记录保存成功');
		}else if($submit=='done'){
			// 状态验证
			if($order['status']!=20 || !($order['staff_status']>0)){
				$this->error('订单状态发生变化，请刷新后重试');
			}

			// 设置为完成状态
			$ret = $this->OrderModel->save(['status'=>30,'status_time'=>time()],['app_id'=>$this->app_id,'id'=>$order['id'],'status_time'=>$order['status_time']]);
			if(!($ret>0)){
				$this->error("操作失败，请重试1");
			}

			// 记录用户订单完成数
			Db::name('vppz_user')->where(['app_id'=>$order['app_id'],'id'=>$order['user_id']])->inc('orders_done',1)->inc('expends',$order['pay'])->update();

			// 分佣并记录
			// 服务者收入
			// profit,profit_fee
			$profit_fee=$order['profit_fee'];
			$profit=$order['profit'];

			//$ret = pdo_query('UPDATE '.tablename('vp_pz_staff') .' SET money=money+:money,income=income+:income,income_service=income_service+:income_service where uniacid = :uniacid AND uid=:uid ', array(':uniacid' => $_W['uniacid'],':uid'=>$mine['uid'],':money'=>$profit_fee,':income'=>$profit_fee,':income_service'=>$profit_fee));

			//$ret = $this->StaffModel->save(['status'=>30,'status_time'=>time()],['app_id'=>$this->app_id,'id'=>$order['id'],'status_time'=>$order['status_time']]);

			if($profit_fee>0){
				$ret = Db::name('vppz_staff')->where(['app_id'=>$this->app_id,'id'=>$order['staff_id']])->inc('money',$profit_fee)->inc('income',$profit_fee)->inc('income_service',$profit_fee)->update();
				if(!($ret>0)){
					$this->error("操作失败，请重试2");
				}
				$this->recordMoney([
					'who'=>'staff',
					'who_id'=>$staff['id'],
					'who_name'=>$staff['nickname'],
					'user_id'=>$mine['id'],
					'money'=> $order['profit_fee'],
					'biz'=>'order',
					'biz_id'=>$order['id'],
					'biz_type'=>'service',
					'biz_name'=>$order['service_name'],
					'remark'=>'订单总价：'.$order['amount'].'元，收益率：'. $profit.'%'
				]);
			}

			// 服务者团长收入
			//tax_master,tax_master_fee
			$master_id=0;
			$tax_master=0;
			$tax_master_fee=0;
			if($staff['master_uid']>0){
				//$master = pdo_fetch('SELECT * FROM ' .tablename('vp_pz_staff') . ' where  uniacid = :uniacid AND uid=:uid ', array(':uniacid' => $_W['uniacid'],':uid'=>$staff['master_uid']));
				$master = $this->StaffModel->where(['app_id'=>$this->app_id,'user_id'=>$staff['master_uid']])->find();
				if($master && $master['master']>0 && $order['tax_master']>0 && $order['tax_master_fee']>0){
					$master_id=$master['id'];
					$tax_master=$order['tax_master'];
					$tax_master_fee=$order['tax_master_fee'];

					//$ret = pdo_query('UPDATE '.tablename('vp_pz_staff') .' SET money=money+:money,income=income+:income,income_master=income_master+:income_master where uniacid = :uniacid AND uid=:uid ', array(':uniacid' => $_W['uniacid'],':uid'=>$master['uid'],':money'=>$tax_master_fee,':income'=>$tax_master_fee,':income_master'=>$tax_master_fee));

					$ret = Db::name('vppz_staff')->where(['app_id'=>$this->app_id,'id'=>$master['id']])->inc('money',$tax_master_fee)->inc('income',$tax_master_fee)->inc('income_master',$tax_master_fee)->update();

					if(!($ret>0)){
						$this->error("操作失败，请重试3");
					}
					$this->recordMoney([
						'who'=>'staff',
						'who_id'=>$master['id'],
						'who_name'=>$master['nickname'],
						'user_id'=>$master['user_id'],
						'money'=> $tax_master_fee,
						'biz'=>'order',
						'biz_id'=>$order['id'],
						'biz_type'=>'master',
						'biz_name'=>$order['service_name'],
						'remark'=>'订单总价：'.$order['amount'].'元，收益率：'. $tax_master.'%'
					]);
				}
			}

			// 推广者收入
			$seller_id=$order['seller_id'];
			$tax_seller=$order['tax_seller'];
			$tax_seller_fee=$order['tax_seller_fee'];
			if($seller_id>0 && $tax_seller_fee>0){
				$seller = $this->UserModel->where(['app_id'=>$this->app_id,'id'=>$seller_id])->find();

				$ret = Db::name('vppz_user')->where(['app_id'=>$this->app_id,'id'=>$seller_id])->inc('sells',1)->inc('sell_money',$tax_seller_fee)->inc('sell_income',$tax_seller_fee)->update();

				if(!($ret>0)){
					$this->error("操作失败，请重试4");
				}
				$this->recordMoney([
					'who'=>'seller',
					'who_id'=>$seller['id'],
					'who_name'=>$seller['nickname'],
					'user_id'=>$seller['id'],
					'money'=> $tax_seller_fee,
					'biz'=>'order',
					'biz_id'=>$order['id'],
					'biz_type'=>'seller',
					'biz_name'=>$order['service_name'],
					'remark'=>'订单总价：'.$order['amount'].'元，收益率：'. $tax_seller.'%'
				]);
			}


			// 平台收入
			//tax_plat,tax_plat_fee
			$tax_plat_fee=$order['tax_plat_fee'];
			$tax_plat=$order['tax_plat'];
			if($order['tax_plat']>0){
				$this->recordMoney([
					'who'=>'plat',
					'who_id'=>$this->app_id,
					'who_name'=>'总部',
					'user_id'=>$this->app_id,
					'money'=> $tax_plat_fee,
					'biz'=>'order',
					'biz_id'=>$order['id'],
					'biz_type'=>'plat',
					'biz_name'=>$order['service_name'],
					'remark'=>'订单总价：'.$order['amount'].'元，收益率：'. $tax_plat.'%'
				]);
			}

			// 重新准确计算城市收入
			$tax_area_fee = $order['amount']-$profit_fee-$tax_plat_fee-$tax_master_fee-$tax_seller_fee;

			//$tax_area_fee=$order['tax_area_fee'];
			//$ret = pdo_query('UPDATE '.tablename('vp_pz_area') .' SET plat_in=plat_in+:plat_in,plat_profit=plat_profit+:plat_profit,money=money+:money,money_in=money_in+:money_in where uniacid = :uniacid AND id=:id ', array(':uniacid' => $_W['uniacid'],':id'=>$area['id'],':plat_in'=>$order['amount'],':plat_profit'=>$order['tax_plat_fee'],':money'=>$tax_area_fee,':money_in'=>$tax_area_fee));

			$ret = Db::name('vppz_area')->where(['app_id'=>$this->app_id,'id'=>$area['id']])->inc('plat_in',$order['amount'])->inc('plat_profit',$order['tax_plat_fee'])->inc('money',$tax_area_fee)->inc('money_in',$tax_area_fee)->update();
			if(!($ret>0)){
				$this->error("操作失败，请重试5");
			}
			$this->recordMoney([
				'who'=>'area',
				'who_id'=>$area['id'],
				'who_name'=>$area['name'],
				'user_id'=>$area['user_id'],		// 城市负责人uid，可能为空，只用作记录，收入归城市，不归人
				'money'=> $tax_area_fee,
				'biz'=>'order',
				'biz_id'=>$order['id'],
				'biz_type'=>'area',
				'biz_name'=>$order['service_name'],
				'remark'=>'订单总价：'.$order['amount'].'元'
			]);

			// 更新最终订单分佣计算数据
			 Db::name('vppz_order')->where(['app_id'=>$this->app_id,'id'=>$order['id']])->data(['master_id'=>$master_id,'tax_master'=>$tax_master,'tax_master_fee'=>$tax_master_fee,'tax_area_fee'=>$tax_area_fee])->update();

			$this->success('订单已完成');
		}else{

			if($order['address']){
				$order['address']=unserialize($order['address']);
			}

			//$ret = Db::name('vppz_order')->where(['app_id'=>$this->app_id,'id'=>$order['id']])->inc('amount',1)->update();
			//$order['ret']=$ret;

			$this->success('',array('order'=>$order));
		}

	}

	/**
     * 我的账户记录
     */
	public function moneys(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		// 接单大厅
		$start=input('start');
		if(!isset($start) || empty($start) || intval($start<=0)){
			$start=0;
		}else{
			$start=intval($start);
		}
		$limit=20;

		$where=[
			'app_id'=>$this->app_id,
			'user_id'=>$mine['id'],
			'who'=>'staff'
		];

		$MoneyModel = new \app\admin\model\vppz\Money;
		$list = $MoneyModel->where($where)->limit($start,$limit)->order('id','desc')->select();

		$more=1;
		if(empty($list) || count($list)<$limit){
			$more=0;
		}
		$start+=count($list);

		$this->success('',array(
			'now'=>time(),
			'list'=>$list,
			'start'=>$start,
			'more'=>$more
		));
	}

	/**
     * 提现
     */
	public function outcash(){
		$cfg=$this->_cfg;
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		$form = input('form');
		if(empty($form)){
			$this->error("内容填写有误，请重试");
		}
		$form = json_decode(urldecode($form),true);
		if(!$form){
			$this->error("内容填写有误，请重试");
		}

		$money = floatval($form['money']);
		$channel = $cfg['outcash_channel'];

		// 验证
		if ($money < intval($cfg['outcash_min'])){
			$this->error('单笔提现至少满'.$cfg['outcash_min'].'元');
		}
		if ($money > intval($cfg['outcash_max'])) {
			$this->error('单笔提现最多'.$cfg['outcash_max'].'元');
		}
		if ($money > $staff['money']){
			$this->error('提现金额不能超过账户余额');
		}
		// 距离上传提现是否超过间隔
		//$last_outcash= pdo_fetch("select * from " . tablename('vp_pz_outcash') . " where uniacid=:uniacid and biz='staff' and uid=:uid ORDER BY id DESC  limit 0,1 ",  array(':uniacid' => $_W['uniacid'],':uid' => $mine['uid']));

		$OutcashModel = new \app\admin\model\vppz\Outcash;
		$last_outcash = $OutcashModel->where(['app_id'=>$this->app_id,'biz'=>'staff','user_id'=>$mine['id']])->order('id','DESC')->find();
		if($last_outcash && (time()-$last_outcash['createtime']<$cfg['outcash_sp']*86400)){
			$this->error('提现间隔不能小于'.$cfg['outcash_sp'].'天');
		}

		$name='';
		$account='';
		$realname='';
		if($channel=='wx'){
			// 微信转账
			$account = $form['account'];
			$realname = $form['realname'];

			if(empty($account)){
				$this->error('请填写收款微信账号');
			}

			if(empty($realname)){
				$this->error('请填写收款账号真实姓名');
			}
			$name='微信转账';
		}else if($channel=='ali'){
			// 支付宝转账
			$account = $form['account'];
			$realname = $form['realname'];

			if(empty($account)){
				$this->error('请填写收款支付宝账号');
			}

			if(empty($realname)){
				$this->error('请填写收款账号真实姓名');
			}
			$name='支付宝转账';
		}else if($channel=='bank'){
			// 银行转账
			$name = $form['name'];
			$account = $form['account'];
			$realname = $form['realname'];

			if(empty($name)){
				$this->error('请填写开户银行');
			}

			if(empty($account)){
				$this->error('请填写银行账号');
			}

			if(empty($realname)){
				$this->error('请填写收款账号真实姓名');
			}
		}

		// 根据提现方式验证
		$mobile = $form['mobile'];
		if(empty($mobile)){
			$this->error('请填写您的手机号码');
		}

		// 先账户扣款，提现增款
		$ret = Db::name('vppz_staff')->where(['app_id'=>$this->app_id,'id'=>$staff['id'],'money'=>$staff['money']])->dec('money',$money)->inc('outcash',$money)->update();
		if(!($ret>0)){
			$this->error("操作失败，请重试");
		}


		// 再生成提现申请记录
		$outcash=array(
			'app_id'=>$this->app_id,
			'area_id'=>$staff['area_id'],
			'biz'=>'staff',
			'biz_id'=>$staff['id'],
			'user_id'=>$mine['id'],
			'nickname'=>$staff['nickname'],
			'mobile'=>$mobile,
			'openid'=>$staff['openid'],
			'money'=>$money,
			'money_before'=>$staff['money'],
			'money_after'=>$staff['money']-$money,
			'cash'=>$money,	// 目前没有手续费
			'status'=>0,
			'channel'=>$channel,
			'channel_name'=>$name,
			'channel_account'=>$account,
			'channel_realname'=>$realname,
		);

		$ret=$OutcashModel->save($outcash);
		$outcash['id'] = $OutcashModel->id;
		if(empty($ret) || empty($outcash['id'])){
			$this->error('提现发起失败，请联系客服处理');
		}

		$this->recordMoney([
			'who'=>'staff',
			'who_id'=>$staff['id'],
			'who_name'=>$mine['nickname'],
			'user_id'=>$mine['id'],
			'money'=> 0-$money,
			'biz'=>'outcash',
			'biz_id'=>$outcash['id'],
			'biz_type'=>'outcash',
			'biz_name'=>'提现'.$money.'元',
			'remark'=>$name
		]);

		$this->success('请耐心等待审核，通过后48小时内将对您的账户打款，请留意账户通知');
	}

	// 陪护团队
	public function team(){
		$area=$this->_area;
		$mine=$this->_mine;
		$staff=$this->_staff;

		// 获取该城市的团队说明
		//$team = pdo_fetch('SELECT staff_invite,staff_team,staff_team_intro FROM ' .tablename('vp_pz_city') . ' where  uniacid = :uniacid AND id=:id ', array(':uniacid' => $_W['uniacid'],':id' =>$city['id']));
		//$team['staff_team_intro']=explode_array($team['staff_team_intro']);

		$team=[
			'staff_team'=>$area['staff_team'],
			'staff_team_intro'=>Vpower::explode_array($area['staff_team_intro']),
		];

		// 获取我的团队成员
		//$list = pdo_fetchall('SELECT * FROM ' .tablename('vp_pz_staff') . ' where  uniacid = :uniacid AND master_uid=:master_uid ', array(':uniacid' => $_W['uniacid'],':master_uid'=>$mine['uid']));

		$list = $this->StaffModel->where(['app_id'=>$this->app_id,'master_uid'=>$mine['id']])->select();

		/**
		for($i=0;$i<count($list);$i++){
			$list[$i]['_avatar']=VP_IMAGE_URL($list[$i]['avatar']);
		}
		**/

		// 我的邀请码
		$invite_code = Vpower::pencode($mine['id']);

		$this->success('',array(
			'invite_code'=>$invite_code,
			'team'=>$team,
			'staff'	=> $staff,
			'list'	=> $list
		));
	}


}
